<template>
  <div>
    <el-dialog title="样例" width="400px" :visible.sync="imgopen">
      <img src="@/assets/images/1.png" style="width: 100%;"/>
    </el-dialog>
    <!-- 添加课程 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible="open"
      width="600px"
      append-to-body
      @close="type == 'add' ? cancel() : close()"
    >
      <div class="el-dialog__title flex" slot="title">
        {{
          type == "add" ? "添加课程" : type == "edit" ? "编辑资料" : "基本信息"
        }}
        <div
          @click="imgopen = true"
          class="flex shou yangli"
          style="margin-left: 20px; font-size: 14px"
        >
          <i style="margin: 6px 2px 0 0" class="el-icon-picture-outline"></i
          >样例
        </div>
      </div>
      <el-form
        ref="form"
        :model="form"
        :rules="type == 'add' || type == 'edit' ? rules : {}"
        label-width="80px"
      >
        <el-form-item label="课程名称" prop="courseName">
          <el-input
            v-if="type == 'add' || type == 'edit'"
            v-input-restrict
            show-word-limit
            maxlength="20"
            style="width: 95%"
            v-model="form.courseName"
            placeholder="请输入课程名称"
          />
          <div v-else>{{ form.courseName }}</div>
        </el-form-item>
        <el-form-item label="岗位" prop="postIds">
          <el-select
            v-if="type == 'add' || type == 'edit'"
            clearable
            multiple
            style="width: 95%"
            v-model="form.postIds"
            placeholder="岗位"
            filterable
          >
            <el-option
              v-for="dict in postOptions"
              :key="dict.postId"
              :label="dict.postName"
              :value="dict.postId + ''"
            />
          </el-select>
          <div v-else>{{ form.postNames }}</div>
        </el-form-item>
        <el-form-item label="课程封面" prop="coursePic">
          <div class="uploadCourseCover">
            <div
              v-if="
                (form.coursePic == undefined || form.coursePic == null) &&
                (type == 'add' || type == 'edit')
              "
              class="upload-head"
              @click="editCropper()"
            >
              <div>
                <img src="@/assets/images/add.png" class="add" alt="" />
              </div>
              <div>上传图片</div>
            </div>
            <div
              v-else
              class="upload-head"
              @click="type == 'add' || type == 'edit' ? editCropper() : ''"
            >
              <img v-bind:src="form.coursePic" class="cover" />
            </div>
          </div>
          <div
            v-if="type == 'add' || type == 'edit'"
            style="
              font-size: 12px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #a3a3a3;
              line-height: 22px;
            "
          >
            建议图片比例16:10,支持jpg、png格式,图片小于5M
          </div>
          <vuecut
            :type="2"
            :uuid="form.dirName"
            :courseTemporaryId="form.courseTemporaryId"
            :w="320"
            :h="200"
            :url="form.coursePic"
            @coverResult="coverResult"
            title="图片上传"
            :open.sync="vuecutshow"
          ></vuecut>
        </el-form-item>
        <el-form-item label="时长" prop="studyTime">
          <el-input-number
            v-if="type == 'add' || type == 'edit'"
            :min="0"
            :precision="1"
            :step="0.5"
            controls-position="right"
            v-model="form.studyTime"
          ></el-input-number>
          <span v-else> {{ form.studyTime ? form.studyTime : "0" }}</span>
          时
        </el-form-item>
        <el-form-item label="材料/设备" prop="studyTools">
          <el-input
            v-if="type == 'add' || type == 'edit'"
            v-input-restrict
            style="width: 95%"
            maxlength="500"
            show-word-limit
            :autosize="{ minRows: 5, maxRows: 5 }"
            v-model="form.studyTools"
            type="textarea"
            placeholder="请输入材料/设备"
          />
          <div
            v-else
            style="white-space: pre-wrap"
            v-html="form.studyTools"
          ></div>
        </el-form-item>
        <el-form-item label="课程描述" prop="describe">
          <el-input
            v-if="type == 'add' || type == 'edit'"
            v-input-restrict
            style="width: 95%"
            maxlength="500"
            show-word-limit
            :autosize="{ minRows: 5, maxRows: 5 }"
            v-model="form.describe"
            type="textarea"
            placeholder="请输入课程描述"
          />
          <div
            v-else
            style="white-space: pre-wrap"
            v-html="form.describe"
          ></div>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex; justify-content: flex-end"
      >
        <el-button v-if="type == 'detail'" v-preventReClick @click="close"
          >关 闭</el-button
        >
        <el-button
          v-if="type == 'add' || type == 'edit'"
          v-preventReClick
          @click="type == 'add' ? cancel() : close()"
          >取 消</el-button
        >
        <el-button
          v-if="type == 'add' || type == 'edit'"
          v-preventReClick
          type="primary"
          @click="submitForm"
          >{{ type == "add" ? "添 加" : "确 认" }}</el-button
        >
      </div>
    </el-dialog>
    <div class="courseBaseDialog">
      <el-dialog :visible.sync="dialogVisible" width="420px">
        <div class="el-message-box__header" slot="title">
          <div class="el-message-box__title">
            <span>取消确认</span>
          </div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__container">
            <div class="el-message-box__status el-icon-warning"></div>
            <div class="el-message-box__message">课程内容未保存,确定取消?</div>
          </div>
        </div>

        <div class="el-message-box__btns">
          <el-button size="small" @click="cancelEdit_cancel">取消</el-button>
          <el-button size="small" type="primary" @click="cancelEdit_saveAndExit"
            >退出并保存</el-button
          >
          <el-button size="small" type="primary" @click="cancelEdit_confirm"
            >确定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listPost } from "@/api/system/post";
import {
  queryCourseTemporary,
  addCourseTemporary,
  getPost_course,
  editCourseTemporary,
} from "@/api/course/course";
export default {
  props: {
    open: Boolean,
    courseInfo: Object,
    type: String,
  },
  data() {
    return {
      imgopen: false,
      dialogVisible: false,
      uuid: "",
      vuecutshow: false,
      // 岗位选项
      postOptions: [],
      // 表单参数
      form: {
        courseTemporaryId: undefined,
        courseName: undefined,
        coursePic: undefined,
        studyTime: undefined,
        studyTools: undefined,
        postIds: undefined,
        describe: undefined,
      },
      // 表单校验
      rules: {
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" },
        ],
        postIds: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
      },
      afterSubmit: false,
    };
  },
  watch: {
    open(e) {
      if (e) {
        console.log("课程信息", this.courseInfo, this.type);
        this.afterSubmit = false;
        this.reset();
        if (this.type == "add") {
          /* 刷新岗位列表 */
          this.form.dirName = this.guid();
          this.getPostList();
        } else if (this.type == "edit") {
          /* 刷新岗位列表 */
          this.getPostList();
          //如果是编辑草稿
          if (this.courseInfo.courseTemporaryId) {
            // 获取课程草稿信息
            this.getCourseTemporary();
          }
        } else {
          //如果是为了查看详情
          if (this.courseInfo.courseTemporaryId) {
            // 获取课程草稿信息
            this.getCourseTemporary();
          }
          if (this.courseInfo.courseId) {
            // 获取课程草稿信息
            this.getCourseInfo();
          }
        }
      }
    },
  },
  mounted() {},
  methods: {
    close() {
      this.$emit("update:open", false);
    },
    guid() {
      let uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
          var r = (Math.random() * 16) | 0,
            v = c == "x" ? r : (r & 0x3) | 0x8;
          return v.toString(16);
        }
      );
      return uuid;
    },
    /** 提交按钮 exit为是否需要退出页面*/
    submitForm(exit) {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          let data = { ...this.form };
          data.postIds = data.postIds.join(",");

          let res;
          //   编辑
          if (this.courseInfo.courseTemporaryId) {
            res = await editCourseTemporary(data);
            this.$emit("addSuccess", this.form.id);
          }
          //   添加
          else {
            res = await addCourseTemporary(data);
            this.$emit("addSuccess", res.data.courseTemporaryId);
          }
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: this.type == "add" ? "添加成功" : "编辑成功",
            });
            this.afterSubmit = true;
            this.$emit("update:open", false);
          }
          if (exit == "exit") {
            console.log("exit");
            this.$router.go(-1);
            this.$tab.closePage();
          }
        }
      });
    },
    /* 取消编辑 */
    cancelEdit_cancel() {
      this.dialogVisible = false;
      // 用户点击了取消按钮
    },
    cancelEdit_confirm() {
      // 用户点击了确定按钮 把整个页面关掉
      this.$router.go(-1);
      this.$tab.closePage();
    },
    cancelEdit_saveAndExit() {
      // 用户点击了退出并保存按钮 保存基本信息把整个页面关掉
      this.submitForm("exit");
    },
    /* 获取课程信息 */
    async getCourseInfo() {
      const res = await getPost_course(this.courseInfo.courseId);
      if (res.code == 200) {
        this.form = res.data;
      }
    },
    /* 获取课程草稿信息 */
    async getCourseTemporary() {
      const res = await queryCourseTemporary(this.courseInfo.courseTemporaryId);
      if (res.code == 200) {
        res.data.postIds = res.data.postIds ? res.data.postIds.split(",") : [];
        this.form = res.data;
      }
    },
    /* 取消按钮 */
    cancel() {
      console.log("触发了cancel", this.afterSubmit);
      if (this.afterSubmit) {
        this.$emit("update:open", false);
        return false;
      }
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          // if (this.form.postIds && this.form.courseName) {

          // } else {

          // }
          this.dialogVisible = true;
        } else {
          this.$router.go(-1);
          this.$tab.closePage();
        }
      });
    },
    coverResult(e) {
      this.form.coursePic = e;
    },
    editCropper() {
      this.vuecutshow = true;
    },
    /* 获取岗位 */
    getPostList() {
      listPost({
        pageNum: 1,
        pageSize: 9999,
      }).then((response) => {
        this.postOptions = response.rows;
      });
    },

    // 表单重置
    reset() {
      this.form = {
        courseTemporaryId: undefined,
        courseName: undefined,
        coursePic: undefined,
        studyTime: undefined,
        studyTools: undefined,
        postIds: undefined,
        describe: undefined,
      };
      this.resetForm("form");
    },
  },
};
</script>
<style scoped lang="scss">
.courseBaseDialog {
  ::v-deep .el-dialog .el-dialog__header {
    border-bottom: none;
    padding: 0 !important;
  }

  ::v-deep .el-message-box__btns .el-button {
    margin-left: 10px;
  }

  ::v-deep .el-message-box__btns {
    padding-bottom: 10px;
  }

  ::v-deep .el-dialog .el-dialog__body {
    padding: 0px !important;
  }
}

.uploadCourseFramePic {
  .uploadTip {
    line-height: 160px;
    height: 100px;
  }

  .upload-head {
    width: 102px;
    height: 102px;

    .add {
      width: 20px;
      height: 20px;
      margin: 25px auto 0 auto;
    }

    .cover {
      width: 100px;
      height: 100px;
    }
  }

  .upload-head:hover:after {
    line-height: 100px;
  }
}

// 上传封面样式
.uploadCourseCover {
  .uploadTip {
    line-height: 160px;
    height: 100px;
  }

  .upload-head {
    width: 162px;
    height: 102px;

    .add {
      width: 20px;
      height: 20px;
      margin: 25px auto 0 auto;
    }

    .cover {
      width: 160px;
      height: 100px;
    }
  }

  .upload-head:hover:after {
    line-height: 100px;
  }
}
</style>